package kr.ac.kd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.kd.JSONObject;

public class ServerCommunicator {

	public static ServerResponse send(ServerRequest request) throws ServerResponseException {
		
		
	    StringBuilder builder = new StringBuilder();
	    HttpClient client = new DefaultHttpClient();
        String respString = null;
        
	    try {
	      System.out.println("new JSONObject(request).toString() : " + new JSONObject(request).toString());
		  HttpPost httpPost = new HttpPost((String)request.getParam("URL"));
		  String stringEntityBody = new String(Base64.encodeBase64(new JSONObject(request).toString().getBytes()));
		  httpPost.setEntity(new StringEntity(stringEntityBody));
	      HttpResponse response = client.execute(httpPost); 
	      StatusLine statusLine = response.getStatusLine();
	      
	      int statusCode = statusLine.getStatusCode();
	      
	      if (statusCode == 200) {
	    	  
	        HttpEntity entity = response.getEntity();
	        InputStream content = entity.getContent();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	        String line;
	        
	        while ((line = reader.readLine()) != null) {
	          builder.append(line.trim());
	        }
	        
	        respString = new String(builder.toString().getBytes("UTF-8"));
	        
	      }else{
	    	  throw new ServerResponseException();
	      }
	    } catch (ClientProtocolException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    
	    return new ServerResponse(respString);	    
	}
}

